package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import org.checkerframework.checker.index.qual.SubstringIndexBottom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.logging.SimpleFormatter;

import static java.lang.String.format;


@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;


    //在这一层干的事情就是将图片文件上传到服务器上
    @Override
    public String upload(MultipartFile file) {
        //获取桶的名字
        String bucketName = minioProperties.getBucketName();
        //判断桶是否存在
        try {
            boolean result = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!result) {
                //如果不存在，创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                //设置访问策略（权限）
                String policy = """
                        {
                                      "Statement" : [ {
                                        "Action" : "s3:GetObject",
                                        "Effect" : "Allow",
                                        "Principal" : "*",
                                        "Resource" : "arn:aws:s3:::%s/*"
                                      } ],
                                      "Version" : "2012-10-17"
                                    }
                        """.format(bucketName);
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policy).build());
            } else {
                //存在
            }

            //设置文件的别名(目的是为了防止文件名重复，所以这里使用uuid作为别名)
            String fileName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID() + "." + file.getOriginalFilename();

            //上传文件
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .object(fileName)
                    .contentType(file.getContentType())
                    .build());


            return String.join("/" ,minioProperties.getEndpoint(), minioProperties.getBucketName(), fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
